package com.cennavi.list;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cennavi.dbs.MongoPool;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

import net.sf.json.JSONObject;

public class DataAttrList extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4178274509719295091L;

	/**
	 * Constructor of the object.
	 */
	public DataAttrList() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS, DELETE,PUT");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		try {

			String jsonStr = request.getParameter("request");

			JSONObject json = JSONObject.fromObject(jsonStr);
			
			String dataType = json.getString("name");
			
//			String coord = json.getString("coord");

			String table = "meta_data";


			DBCollection collection = MongoPool.getDB().getCollection(table);

			DBCursor cursor = collection.find((DBObject) JSON.parse("{'name':'"+dataType+"'}"),
					(DBObject) JSON.parse("{'_id':" + 0 + "}"));


			

//			out.println("[");

			boolean flag = false;

			while (cursor.hasNext()) {

				if (!flag) {
					flag = true;
					out.println(cursor.next());
				} else {
					out.println("," + cursor.next());
				}
			}

//			out.println("]");

			

		} catch (Exception e) {
			out.println("{\"error_code\":-1,\"error_msg\":\"" + e.getMessage()
					+ "\"}");
		} finally {
			out.flush();

			out.close();
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}

}
